package com.zb.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.zb.common.R;
import com.zb.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        String url = req.getRequestURL().toString(); //请求路径
        //登录请求直接放行
        if (url.contains("login")) {
            return true;
        }

        //获取token
        String token = req.getHeader("token");
        //请求头没有token
        if (!StringUtils.hasLength(token)) {
            R err = R.error("NOT LOGIN");
            //错误数据转字符串
            String notLogin = JSONObject.toJSONString(err);
            res.getWriter().write(notLogin);
            return false;
        }

        //token无效
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            R err = R.error("NOT LOGIN");
            //错误数据转字符串
            String notLogin = JSONObject.toJSONString(err);
            res.getWriter().write(notLogin);
            return false;
        }

        return true;
    }
}
